import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import RFE
from imblearn.over_sampling import SMOTE

# 加载数据
data = pd.read_excel("files/data.xlsx")
X = data.iloc[:, :-1]
y = data.iloc[:, -1]

# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)

# 特征选择
selector = RFE(estimator=LogisticRegression(solver='liblinear'), n_features_to_select=20)
X_selected = selector.fit_transform(X, y)

# 二分类任务 AD vs EMCI
binary_data = data[(data.iloc[:, -1] == 'AD') | (data.iloc[:, -1] == 'EMCI')]
X_binary = binary_data.iloc[:, :-1]
y_binary = binary_data.iloc[:, -1]
y_binary = y_binary.map({'AD': 1, 'EMCI': 0})  # 将类别转换为0和1

# 数据标准化
scaler = StandardScaler()
X_binary = scaler.fit_transform(X_binary)

# 数据重采样以处理类别不平衡
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X_binary, y_binary)

# 数据分割
X_train, X_test, y_train, y_test = train_test_split(X_resampled, y_resampled, test_size=0.2, random_state=42)

# 定义模型和参数网格
param_grid = {
    'C': [0.01, 0.1, 1, 10, 100],  # 正则化强度
    'penalty': ['l1', 'l2'],        # 正则化方式
    'solver': ['liblinear', 'saga'] # 优化算法
}

# 创建逻辑回归模型
logistic_model = LogisticRegression(max_iter=10000)

# 网格搜索
grid_search = GridSearchCV(estimator=logistic_model, param_grid=param_grid, cv=5, scoring='accuracy')
grid_search.fit(X_train, y_train)

# 输出最优参数和模型
print("最优参数:", grid_search.best_params_)
best_model = grid_search.best_estimator_

# 使用最优模型进行预测
y_pred = best_model.predict(X_test)

# 计算并输出准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'分类任务 AD vs EMCI 的准确率: {accuracy}')
